package com.fyzk.activity.popupwindow;

import android.app.ProgressDialog;
import android.content.Context;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.fyzk.activity.app.App;
import com.fyzk.activity.app.AppToast;
import com.fyzk.bean.StringResultBean_New;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.net.PublicMethod;
import com.fyzk.net.ToolsAesCrypt;
import com.fyzk.utils.AppUtil;
import com.fyzk.utils.Base64;
import com.fyzk.utils.LogUtil;
import com.wf.domain.UrlDef;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.http.body.RequestBody;
import org.xutils.x;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import http.DataUtil.text.TextUtil;
import http.StringResultBean;
import http.XRequestCallBack;
import razerdp.basepopup.BasePopupWindow;

public abstract class BaseRequestPopupWindow extends BasePopupWindow {

    protected final String TAG = this.getClass().getSimpleName();
    protected String url = UrlDef.TY_URL_NEW_DATA;

    public BaseRequestPopupWindow(Context context) {
        super(context);
    }

    public BaseRequestPopupWindow(Context context, boolean delayInit) {
        super(context, delayInit);
    }

    public BaseRequestPopupWindow(Context context, int width, int height) {
        super(context, width, height);
    }

    public BaseRequestPopupWindow(Context context, int width, int height, boolean delayInit) {
        super(context, width, height, delayInit);
    }

    /**
     * post请求
     *
     * @param requestCode
     * @param params
     * @param showProgress 是否显示加载提示
     */
    public void httpPostJson(int requestCode, String command, JSONObject params,
                             boolean showProgress) {
        sendRequestUseJson(requestCode, command, params, showProgress, this.url);
    }

    /**
     * post请求
     *
     * @param requestCode
     * @param params
     * @param showProgress 是否显示加载提示
     */
    public void httpPostJson(int requestCode, String command, JSONObject params,
                             boolean showProgress, String url) {
        sendRequestUseJson(requestCode, command, params, showProgress, url);
    }

    /**
     * post请求(返回结果不加密)
     *
     * @param requestCode
     * @param params
     * @param showProgress 是否显示加载提示
     */
    public void httpPostJsonNo(int requestCode, String command, JSONObject params,
                               boolean showProgress, String url) {
        sendRequestJson(requestCode, command, params, showProgress, url);
    }

    protected void onSuccess(int requestCode,
                             StringResultBean resultBean, String result) {

    }


    protected void onSuccess(int requestCode, StringResultBean_New resultBean, String
            result) {
    }

    protected void onSuccess(int requestCode, String result) {

    }

    protected void onFailure(int requestCode) {
        onFailure(requestCode, "");
    }

    protected void onFailure(int requestCode, String message) {
        onFailure(requestCode, "", message);
    }

    protected void onFailure(int requestCode, String errorCode, String message) {
        cancelProgressDialog();
        if (!TextUtils.isEmpty(message)) {
            AppToast.getToast().show(message);
        }
    }

    protected void onFailure(StringResultBean resultBean, int requestCode, String errorCode,
                             String message) {
        onFailure(requestCode, errorCode,
                message);
    }


    Map<String, XRequestCallBack<String>> callBackMap = new HashMap<>();

    /**
     * U粉通接口 使用json请求数据
     *
     * @param requestCode
     * @param params2
     * @param showProgress
     */
    public void sendRequestUseJson(final int requestCode, String command,
                                   JSONObject params2, final boolean showProgress, String url) {
        if (!AppUtil.isNetworkAvailable(getContext())) {
            AppToast.getToast().show("网络错误!");
            this.onFailure(requestCode, "网络错误!");
            return;
        }
        if (showProgress) {
            showProgressDialog();
        }
        XRequestCallBack<String> callBack = callBackMap.get(requestCode + "");
        if (callBack == null) {
            callBack = new XRequestCallBack<String>(requestCode) {
                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    super.onError(ex, isOnCallback);
                    LogUtil.d("联网失败:" + ex.getMessage());
                    BaseRequestPopupWindow.this.onFailure(getRequestCode(), null);
                    if (showProgress) {
                        cancelProgressDialog();
                    }
                }

                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);
                    String netResult = null;
                    String decode_ = null;
                    LogUtil.d("联网返回成功:" + result);
                    if (showProgress) {
                        cancelProgressDialog();
                    }
                    try {
                        decode_ = ToolsAesCrypt.Decrypt(result.substring(1, result.length() - 1),
                                UrlDef.stringFromJNI());
                        System.out.println("decode>" + decode_);
                        byte[] base64d = Base64.decode(decode_);
                        byte[] decompress = PublicMethod.decompress2(base64d);
                        netResult = new String(decompress, "utf-8");

                        LogUtil.d("联网：解密后返回>" + requestCode + ">" + netResult.toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    try {
                        if (showProgress) {
                            cancelProgressDialog();
                        }
                        StringResultBean resultBean = JSON.parseObject(netResult,
                                StringResultBean.class);
                        if (resultBean.getErrorcode().equals("0")) {
                            LogUtil.e("success>>>>>>");
                            BaseRequestPopupWindow.this.onSuccess(getRequestCode(), resultBean,
                                    netResult);
                        } else if (resultBean.getErrorcode().equals("110003")) {
                            MySharedPreferences.getInstance().setAuthToken("");
                            BaseRequestPopupWindow.this.onFailure(resultBean, getRequestCode(), resultBean
                                    .getErrorcode(), resultBean.getMsg());
                        } else {
                            LogUtil.e("fail>>>>>>");
                            BaseRequestPopupWindow.this.onFailure(resultBean, getRequestCode(), resultBean
                                    .getErrorcode(), resultBean.getMsg());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        if (showProgress) {
                            cancelProgressDialog();
                        }
                        LogUtil.d("BaseActivity >>  result 数据异常。。");
                        StringResultBean bean = null;
                        BaseRequestPopupWindow.this.onSuccess(getRequestCode(), bean,
                                netResult);
                    }
                    if (showProgress) {
                        cancelProgressDialog();
                    }
                    this.onFinished();

                }
            };
            callBackMap.put(requestCode + "", callBack);
        }


        RequestParams params = new RequestParams(url);
        //打印请求
        try {
            JSONObject requstJson = new JSONObject();

            JSONObject clientInfo = new JSONObject();
            long timestamp = System.currentTimeMillis();


            String token = http.DataUtil.md5.MD5.toMd5(http.DataUtil.md5.MD5.toMd5((UrlDef
                    .stringFromJNI() +
                    timestamp).getBytes()).getBytes());
            clientInfo.put("agentId", App.getChannel());
            clientInfo.put("apn", "WIFI");
            clientInfo.put("authtoken", MySharedPreferences.getInstance().getAuthtoken());
            clientInfo.put("model", "android");
            clientInfo.put("platform", "android");
            clientInfo.put("timestamp", timestamp);
            clientInfo.put("token", token);
            clientInfo.put("version", App.getVersionName());
            String branch = MySharedPreferences.getInstance().getBranch();
            String companyid = MySharedPreferences.getInstance().getCompanyid();
            if (TextUtil.isEmpty(branch)) {
                branch = App.BRANCH;
                MySharedPreferences.getInstance().setBranch(App.BRANCH);
            }
            if (TextUtil.isEmpty(companyid)) {
                companyid = App.COMPANYID;
                MySharedPreferences.getInstance().setCompanyid(App.COMPANYID);
            }
            clientInfo.put("branch", branch);
            clientInfo.put("companyid", companyid);
            requstJson.put("clientInfo", clientInfo);
            requstJson.put("command", command);
            if (params2 == null) params2 = new JSONObject();
            params2.put("sysCode", "HM");
            requstJson.put("data", params2);
            LogUtil.d("联网：加密前请求>" + requstJson.toString());
            String encrypt = ToolsAesCrypt.Encrypt(requstJson.toString(), UrlDef.stringFromJNI());
            LogUtil.d("联网：加密后请求>" + encrypt);
            params.setBodyContent("body=" + encrypt);
            RequestBody body = params.getRequestBody();
            body.setContentType("application/x-www-form-urlencoded");
            params.setRequestBody(body);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.d("加密失败");
        }

        LogUtil.v("联网请求：" + params);
        x.http().post(params, callBack);

    }

    private ProgressDialog progressDialog;

    public void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(getContext());
            progressDialog.setMessage("联网处理中……");
        }
        progressDialog.show();
    }

    protected void cancelProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.cancel();
        }
    }

    /**
     * U粉通接口 使用json请求数据
     *
     * @param requestCode
     * @param method
     * @param params
     * @param showProgress
     */
    public void sendRequest(HttpMethod method, int requestCode, RequestParams params, final
    boolean showProgress) {


        if (!AppUtil.isNetworkAvailable(getContext())) {
            AppToast.getToast().show("网络错误!");
            return;
        }

        if (showProgress) {
            showProgressDialog();
        }

        XRequestCallBack<String> callBack = new XRequestCallBack<String>(
                requestCode) {
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
//                onFailure(getRequestCode(), "网络异常");
                LogUtil.d("请求失败");
                if (showProgress) {
                    cancelProgressDialog();
                }
            }

            @Override
            public void onSuccess(String result) {
                LogUtil.d("联网返回成功：" + result);
                super.onSuccess(result);
                try {
                    StringResultBean resultBean = JSON.parseObject(result,
                            StringResultBean.class);
                    if (resultBean.getErrorcode().equals("0")) {
                        BaseRequestPopupWindow.this.onSuccess(getRequestCode(), resultBean,
                                result);
                    } else {
                        onFailure(getRequestCode(), resultBean.getErrorcode(), resultBean
                                .getMessage());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    BaseRequestPopupWindow.this.onFailure(getRequestCode(), "9999",
                            "数据异常");
                }
                if (showProgress) {
                    cancelProgressDialog();
                }

            }
        };

        LogUtil.v("联网请求：" + params);
        if (method == HttpMethod.POST) {
            x.http().post(params, callBack);
        }
//        else if (method == HttpMethod.GET) {
//            x.http().get(params, callBack);
//        } else {
//            x.http().post(params, callBack);
//        }

    }


    /**
     * U粉通接口 使用json请求数据
     *
     * @param requestCode
     * @param method
     * @param params
     * @param showProgress
     */
    public void sendRequestGet(HttpMethod method, int requestCode, RequestParams params,
                               final boolean showProgress) {

        if (!AppUtil.isNetworkAvailable(getContext())) {
            AppToast.getToast().show("网络错误!");
            return;
        }

        if (showProgress) {
            showProgressDialog();
        }

        XRequestCallBack<String> callBack = new XRequestCallBack<String>(
                requestCode) {
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                LogUtil.d("请求失败");
                if (showProgress) {
                    cancelProgressDialog();
                }
            }

            @Override
            public void onSuccess(String result) {
                LogUtil.d("联网返回成功：" + result);
                super.onSuccess(result);
                BaseRequestPopupWindow.this.onSuccess(getRequestCode(), result);
                if (showProgress) {
                    cancelProgressDialog();
                }

            }
        };

        LogUtil.v("联网请求：" + params);
        if (method == HttpMethod.GET) {
            x.http().get(params, callBack);
        } else {
            x.http().post(params, callBack);
        }
    }

    /**
     * U粉通接口 使用json请求数据（返回结果没有加密）
     *
     * @param requestCode
     * @param params2
     * @param showProgress
     */
    public void sendRequestJson(final int requestCode, String command,
                                JSONObject params2, final boolean showProgress, String url) {
        if (!AppUtil.isNetworkAvailable(getContext())) {
            AppToast.getToast().show("网络错误!");
            this.onFailure(requestCode, "网络错误!");
            return;
        }
        if (showProgress) {
            showProgressDialog();
        }
        XRequestCallBack<String> callBack = callBackMap.get(requestCode + "");
        if (callBack == null) {
            callBack = new XRequestCallBack<String>(requestCode) {
                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    super.onError(ex, isOnCallback);
                    LogUtil.d("联网失败:" + ex.getMessage());
                    BaseRequestPopupWindow.this.onFailure(getRequestCode(), null);
                    if (showProgress) {
                        cancelProgressDialog();
                    }
                }

                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);
                    LogUtil.d("联网返回成功:" + result);
                    if (showProgress) {
                        cancelProgressDialog();
                    }

                    try {
                        if (showProgress) {
                            cancelProgressDialog();
                        }
                        StringResultBean resultBean = JSON.parseObject(result,
                                StringResultBean.class);
                        if (resultBean.getErrorcode().equals("0")) {
                            LogUtil.e("success>>>>>>");
                            BaseRequestPopupWindow.this.onSuccess(getRequestCode(), resultBean,
                                    result);
                        } else if (resultBean.getErrorcode().equals("110003")) {
                            MySharedPreferences.getInstance().setAuthToken("");
                            MySharedPreferences.getInstance().setLoginStatus(false);
                            BaseRequestPopupWindow.this.onFailure(resultBean, getRequestCode(), resultBean
                                    .getErrorcode(), resultBean.getMsg());
                        } else {
                            LogUtil.e("fail>>>>>>");
                            BaseRequestPopupWindow.this.onFailure(resultBean, getRequestCode(), resultBean
                                    .getErrorcode(), resultBean.getMsg());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        if (showProgress) {
                            cancelProgressDialog();
                        }
                        LogUtil.d("BaseActivity >>  result 数据异常。。");
                        StringResultBean bean = null;
                        BaseRequestPopupWindow.this.onSuccess(getRequestCode(), bean,
                                result);
                    }
                    if (showProgress) {
                        cancelProgressDialog();
                    }
                    this.onFinished();

                }
            };
            callBackMap.put(requestCode + "", callBack);
        }


        RequestParams params = new RequestParams(url);
        //打印请求
        try {
            JSONObject requstJson = new JSONObject();

            JSONObject clientInfo = new JSONObject();
            long timestamp = System.currentTimeMillis();


            String token = http.DataUtil.md5.MD5.toMd5(http.DataUtil.md5.MD5.toMd5((UrlDef
                    .stringFromJNI() +
                    timestamp).getBytes()).getBytes());
            clientInfo.put("agentId", App.getChannel());
            clientInfo.put("apn", "WIFI");
            clientInfo.put("authtoken", MySharedPreferences.getInstance().getAuthtoken());
            clientInfo.put("model", "android");
            clientInfo.put("platform", "android");
            clientInfo.put("timestamp", timestamp);
            clientInfo.put("token", token);
            clientInfo.put("version", App.getVersionName());
            String branch = MySharedPreferences.getInstance().getBranch();
            String companyid = MySharedPreferences.getInstance().getCompanyid();
            if (TextUtil.isEmpty(branch)) {
                branch = App.BRANCH;
                MySharedPreferences.getInstance().setBranch(App.BRANCH);
            }
            if (TextUtil.isEmpty(companyid)) {
                companyid = App.COMPANYID;
                MySharedPreferences.getInstance().setCompanyid(App.COMPANYID);
            }
            clientInfo.put("branch", branch);
            clientInfo.put("companyid", companyid);
            requstJson.put("clientInfo", clientInfo);
            requstJson.put("command", command);
            if (params2 == null) params2 = new JSONObject();
            params2.put("sysCode", "HM");
            requstJson.put("data", params2);
            LogUtil.d("联网：加密前请求>" + requstJson.toString());
            String encrypt = ToolsAesCrypt.Encrypt(requstJson.toString(), UrlDef.stringFromJNI());
            LogUtil.d("联网：加密后请求>" + encrypt);
            params.setBodyContent("body=" + encrypt);
            RequestBody body = params.getRequestBody();
            body.setContentType("application/x-www-form-urlencoded");
            params.setRequestBody(body);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.d("加密失败");
        }

        LogUtil.v("联网请求：" + params);
        x.http().post(params, callBack);

    }
}
